package cfca.paperless.client.servlet._2_extend._2_01_AutoCalculatePdfHash;

import java.io.File;
import java.io.FileInputStream;
import java.security.PrivateKey;
import java.util.Date;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessConfig;
import cfca.paperless.client.util.GUID;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PaperlessUtil;
import cfca.paperless.client.util.StrategyUtil;
import cfca.paperless.client.util.StringUtil;
import cfca.sadk.algorithm.common.Mechanism;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.util.Base64;
import cfca.sadk.util.KeyUtil;
import cfca.sadk.util.Signature;
import cfca.sadk.x509.certificate.X509Cert;

public class AutoCalculatePdfHashTest03 {

    /**
     * 自动化计算PDF签章HASH值接口，内容类型为hashBase64,使用固定证书签名
     * @param args
     * @throws IOException
     * @throws
     */
    public static void main(String[] args) throws Exception {
        try {
            long timeStart = System.currentTimeMillis();// 开始时间
            //初始化客户端对象
            PaperlessClient clientBean = new PaperlessClient(PaperlessConfig.extUrl, 10000, 60000);// 无纸化辅助接口的访问URL

            //待计算hash的pdf
            String filePath = "./TestData/autoCalculatePdfHash.pdf";
           
            String pdfSuffix = IoUtil.getFileNameSuffix(filePath);
            if(!PaperlessConfig.PDF_FILE_SUFFIX.equals(pdfSuffix)){
                throw new Exception("所选文件不是pdf文件");
            }
            byte[] pdf = FileUtils.readFileToByteArray(new File(filePath));
            //公钥证书
            byte[] x509Cert =FileUtils.readFileToByteArray(new File("./TestData/cert/11111111.cer"));
            X509Cert cert = new X509Cert(x509Cert);
            //私钥
            PrivateKey privateKey = KeyUtil.getPrivateKeyFromPFX(new FileInputStream("./TestData/cert/11111111.pfx"), "11111111");
 
            String sealImagePath = "./TestData/zhangfei.png";
            
            String pngSuffix = IoUtil.getFileNameSuffix(sealImagePath);
            if(!PaperlessConfig.PNG_FILE_SUFFIX.equals(pngSuffix)){
                throw new Exception("所选文件不是png文件,签章图片文件只支持png格式图片");
            }
            
            //印模图片
            byte[] sealImage = FileUtils.readFileToByteArray(new File(sealImagePath));
            //签章位置
            SignLocation signLocation = new SignLocation("代理人签名", "R", 20, -5);
            // 策略文件
            String strategyXml = StrategyUtil.createClientSealStrategyXml("业务", "china", sealImage, signLocation, "sha1", "hashBase64");
            // 操作员编码或者机构号
            String operatorCode = PaperlessConfig.operatorCode;
            // 渠道编码，可以为空
            String channelCode = PaperlessConfig.channelCode;
            String systemNo = GUID.generateId();//业务流水号 
            //计算hash x509Cert参数可以为空，为空时外部合成签名只能是pkcs7
            String returnMessage = clientBean.autoCalculatePdfHash(systemNo,pdf, x509Cert,strategyXml, operatorCode, channelCode);

            String code = StringUtil.getNodeText(returnMessage, "Code");
            if ("200".equals(code)) {
                System.out.println("OK:autoCalculatePdfHash");
                String pdfHash = StringUtil.getNodeText(returnMessage, "PdfHash");//pdf签名hash的base64值
                String id = StringUtil.getNodeText(returnMessage, "Id");//标识,用来对应后台的缓存数据
                System.out.println("返回的PDF文档HASH值：" + pdfHash);
                System.out.println("返回的ID：" + id);
                
                JCrypto.getInstance().initialize(JCrypto.JSOFT_LIB, null);
                cfca.sadk.lib.crypto.Session mySession = JCrypto.getInstance().openSession(JCrypto.JSOFT_LIB);
                Signature sigUtil = new Signature();
                //对hashBase64进行签名
                byte[] signature = sigUtil.p7SignMessageDetach(Mechanism.SHA1_RSA, pdfHash.getBytes(), privateKey, new X509Cert(x509Cert), mySession);
                System.out.println("signature:" + new String(signature));

                byte[] sealedPdfData = clientBean.synthesizeOuterSignature(systemNo,Base64.decode(signature), id, operatorCode, channelCode);
                String errorRsString = PaperlessUtil.isError(sealedPdfData);
                if ("".equals(errorRsString)) {
                    System.out.println("OK:synthesizeOuterSignature");
                    System.out.println(sealedPdfData.length);
                    IoUtil.write("./TestData/output/sealedPdf-" + new File(filePath).getName() + ".pdf", sealedPdfData);
                } else {
                    // 处理结果为异常，打印出错误码和错误信息
                    System.out.println("NG:synthesizeOuterSignature");
                    System.out.println(sealedPdfData.length);
                    System.out.println(new String(sealedPdfData, "UTF-8"));
                }
                long timeEnd = System.currentTimeMillis();// 结束时间
                System.out.println("time:" + (timeEnd - timeStart));
            } else {
                System.out.println("获得PDF文档HASH值失败！" + returnMessage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
